package com.monicash.monicash.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.cirno_poi.verifyedittextlibrary.VerifyEditText;
import com.google.gson.Gson;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.monicash.monicash.R;
import com.monicash.monicash.base.BaseActivity;
import com.monicash.monicash.bean.InitZiLiPageDeviceSeed;
import com.monicash.monicash.login.modle.LoginModle;
import com.monicash.monicash.util.IntentUtils;
import com.monicash.monicash.util.T;
import com.xx.text.tool.encipher.Base64Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VerifyActivity extends BaseActivity {

    TextView back;
    TextView right_text;
    VerifyEditText verifyedittext;
    TextView tv_describe;
    TextView tv_button;
    private String password = "";
    private String password_confirm = "";
    String keyword = "";
    String contentText = "";
    String account = "";
    String type = "";
    int isShowCode = 1;
    String code = "";
    LoginModle loginModle = null;
    InitZiLiPageDeviceSeed databean = null;

    public List<String> permissions = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify);
        Intent intent = getIntent();
        if (intent != null) {
            String ss = intent.getStringExtra("account");
            String type = intent.getStringExtra("type");
            if (ss != null) {
                account = ss;
            }
            if (type != null) {
                this.type = type;
            }
        }
        loginModle = LoginModle.Companion.getInstant();
        initView();
        initData();

    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void initView() {
        back = findViewById(R.id.back);
        right_text = findViewById(R.id.right_text);
        verifyedittext = findViewById(R.id.verifyedittext);
        tv_describe = findViewById(R.id.tv_describe);
        tv_button = findViewById(R.id.tv_button);

        keyword = this.getString(R.string.verify_keyword_code);
        contentText = this.getString(R.string.verify_text_string_code);
        getContentText();
        tv_describe.setMovementMethod(LinkMovementMethod.getInstance());
        tv_describe.setText(getSpannableString1());

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                code = verifyedittext.getContent();
                if (TextUtils.isEmpty(code)) {
                    T.showShort(getActivity(), "验证码不完整");
                }
                verifyZiLiPageSmsCodeForOTP();
            }
        });

        permissions.add(Permission.READ_SMS);
        permissions.add(Permission.READ_CALL_LOG);
        setPermissionList(permissions);
        getPermissions();

    }


    @Override
    public void initData() {
        initZiLiPageDeviceSeed();

    }

    private SpannableString getSpannableString1() {
        int indexKeyword1Start = contentText.indexOf(keyword);
        int indexKeyword1End = indexKeyword1Start + keyword.length();
        SpannableString spannableString = new SpannableString(contentText);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                if (isShowCode == 2) {
                    keyword = VerifyActivity.this.getString(R.string.verify_keyword_phone);
                    contentText = VerifyActivity.this.getString(R.string.verify_text_string_phone);
                    getContentText();
                    isShowCode = 1;
                } else {
                    keyword = VerifyActivity.this.getString(R.string.verify_keyword_code);
                    contentText = VerifyActivity.this.getString(R.string.verify_text_string_code);
                    getContentText();
                    isShowCode = 2;
                }
                tv_describe.setText(getSpannableString1());
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(VerifyActivity.this.getColor(R.color.blue_00daf7));// 字体颜色
                ds.setUnderlineText(false); // 是否有下划线
            }
        }, indexKeyword1Start, indexKeyword1End, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    public void getContentText() {
        if (contentText.contains("95652886")) {
            contentText = contentText.replace("95652886", account);
        }
    }

    public void initZiLiPageDeviceSeed() {
        String data = loginModle.initZiLiPageDeviceSeed(this);
        databean = new Gson().fromJson(data, InitZiLiPageDeviceSeed.class);
        securitygetSmsCode();
    }

    private void securitygetSmsCode() {
        Map<String, String> params = new HashMap<String, String>();

        params.put("mobile", account);
        params.put("scenes", "register");

        if (databean != null && databean.getData()!=null) {
            String token =  loginModle.getZiLiPage_App_ID()+ databean.getData().getSeed() +
                    System.currentTimeMillis() / 1000;
            try {
                MessageDigest md = MessageDigest.getInstance("SHA1");
                md.update(token.getBytes());
                String anonymousToken = Base64Utils.INSTANCE.encode(md.digest());

                String data = loginModle.getZiLiPageSmsCode(this,
                        account, String.valueOf(isShowCode), code,anonymousToken);

                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (loginModle.isSuccess(jsonObject)) {
                        JSONObject optJSONObject = jsonObject.optJSONObject("data");
                        if (TextUtils.equals(optJSONObject.optString("smsType"), "2")) {
                            T.showShort(VerifyActivity.this,optJSONObject.optString("msg"));
                        } else {
                            T.showShort(VerifyActivity.this,optJSONObject.optString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void verifyZiLiPageSmsCodeForOTP(){
        String ss = loginModle.verifyZiLiPageSmsCodeForOTP(account,code,getActivity());
        try {
            JSONObject data = new JSONObject(ss);
            if (loginModle.isSuccess(data)) {
                JSONObject bean = data.getJSONObject("data");
                if (loginModle.getBooleanToJson(bean, "flag")) {
                    switch (type) {
                        case "1":
                            Intent intent = new Intent(VerifyActivity.this, RegisterActivity.class);
                            intent.putExtra("account", account);
                            intent.putExtra("type", "1");
                            startActivity(intent);
                            finish();
                            break;
                    }

                } else {
                    Intent intent = new Intent(VerifyActivity.this, RegisterActivity.class);
                    intent.putExtra("account", account);
                    intent.putExtra("type", "1");
                    startActivity(intent);
                    finish();
                    T.showShort(getActivity(), loginModle.getStringToJson(data, "msg"));
                }
            }
            Intent intent = new Intent(VerifyActivity.this, RegisterActivity.class);
            intent.putExtra("account", account);
            intent.putExtra("type", "1");
            startActivity(intent);
            finish();
        } catch (JSONException e) {
            e.printStackTrace();
            Intent intent = new Intent(VerifyActivity.this, RegisterActivity.class);
            intent.putExtra("account", account);
            intent.putExtra("type", "1");
            startActivity(intent);
            finish();
        }
    }


}
